package com.mo.lib.utils

import android.Manifest
import android.app.Notification
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.provider.Settings
import android.webkit.MimeTypeMap
import androidx.annotation.RequiresPermission
import com.dylanc.longan.appName
import com.dylanc.longan.packageName
import com.dylanc.longan.startForActivity
import com.mo.lib.AppMarkers
import com.mo.lib.utils.data.gcj2bd
import com.mo.lib.utils.data.getLoctionDowble

/**
 * @ author：mo
 * @ data：2022/3/29:16:32
 * @ 功能：
 */

/** 跳设置软件自启动*/
fun Context.toAutoStart() {
    var intent = Intent()

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    var componentName: ComponentName? = null //判断手机型号
    when (Build.BRAND) {
        "Xiaomi" -> componentName = ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity") //小米
        "Letv" -> intent.action = "com.letv.android.permissionautoboot" //乐视
        "samsung" -> componentName = ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm.ui.ram.AutoRunActivity") //三星
        "HUAWEI" -> componentName = ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity") //华为
        "vivo" -> componentName = ComponentName.unflattenFromString("com.iqoo.secure/.safeguard.PurviewTabActivity") //vivo
        "Meizu" -> componentName = ComponentName.unflattenFromString("com.meizu.safe/.permission.PermissionMainActivity") //魅族
        "OPPO" -> componentName = ComponentName.unflattenFromString("com.oppo.safe/.permission.startup.StartupAppListActivity") //OPPO
        "ulong" -> componentName = ComponentName("com.yulong.android.coolsafe", ".ui.activity.autorun.AutoRunListActivity") //360
        else -> {
            if (Build.VERSION.SDK_INT >= 9) {
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", packageName, null)
            } else if (Build.VERSION.SDK_INT <= 8) {
                intent.action = Intent.ACTION_VIEW
                intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails")
                intent.putExtra("com.android.settings.ApplicationPkgName", packageName)
            }
        }
    }
    intent.component = componentName
    try {
        intent.startForActivity()
    } catch (e: Exception) { //抛出异常就直接打开设置页面
        intent = Intent(Settings.ACTION_SETTINGS)
        intent.startForActivity()
    }
}

/** 跳应用市场*/
fun Context.toMarket(marker: AppMarkers = AppMarkers.DEFULT) {
    val uri = Uri.parse(if (marker == AppMarkers.SAMSUN) "http://www.samsungapps.com/appquery/appDetail.as?appId=" else "market://details?id=$packageName")
    val intent = Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // 如果没给市场的包名，则系统会弹出市场的列表让你进行选择。
    if (!marker.markerPath.isEmpty()) {
        intent.setPackage(marker.markerPath)
    }
    try {
        intent.startForActivity()
    } catch (ex: java.lang.Exception) {
        showToast("没有安装${marker.markerName}")
        ex.printStackTrace()
    }
}

/** 跳应用信息*/
fun toAppSetting(packageName1: String = packageName) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.parse("package:$packageName1")).startForActivity()


/**跳网络设置 */
fun toSettingNet() = Intent(Settings.ACTION_WIRELESS_SETTINGS).startForActivity()

/** 跳Wifi设置*/
fun toSettingWifi() = Intent(Settings.ACTION_WIFI_SETTINGS).startForActivity()

/**跳转GPS设置 */
fun toSettingGps() = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).startForActivity()

/**跳应用管理列表 */
fun toAppsManage() = Intent(Settings.ACTION_APPLICATION_SETTINGS).startForActivity()

/** 跳无障碍服务设置*/
fun toSettingAccessibility() = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).startForActivity()

/** 跳应用通知--这个方法会把吐司也关了*/
fun Context.toSettingNotification() {
    var intent = Intent()
    try { // 根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
        intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
        intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
        intent.putExtra(Notification.EXTRA_CHANNEL_ID, applicationInfo.uid) //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
        intent.putExtra("app_package", packageName)
        intent.putExtra("app_uid", applicationInfo.uid)
        intent.startForActivity() // 小米6 -MIUI9.6-8.0.0系统，是个特例，通知设置界面只能控制"允许使用通知圆点"——然而这个玩意并没有卵用，我想对雷布斯说：I'm not ok!!!
        //  if ("MI 6".equals(Build.MODEL)) {
        //      intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //      Uri uri = Uri.fromParts("package", getPackageName(), null);
        //      intent.setData(uri);
        //      // intent.setAction("com.android.settings/.SubSettings");
        //  }
    } catch (e: java.lang.Exception) {
        e.printStackTrace() // 出现异常则跳转到应用设置界面：锤子坚果3——OC105 API25
        //下面这种方案是直接跳转到当前应用的设置界面。
        //https://blog.csdn.net/ysy950803/article/details/71910806
        toAppSetting()
    }
}

/** 跳拨号*/
fun toDial(phoneNumber: String = "") = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phoneNumber")).startForActivity()

/**获取跳转「拨打电话」的意图, 即直接拨打电话,需添加权限 `<uses-permission android:name="android.permission.CALL_PHONE"/>` */
@RequiresPermission(Manifest.permission.CALL_PHONE) fun toCall(phoneNumber: String) = Intent("android.intent.action.CALL", Uri.parse("tel:$phoneNumber")).startForActivity()

/** 跳浏览器*/
fun toBrowser(url: String = "") = Intent().setAction("android.intent.action.VIEW").setData(Uri.parse(if (!url.contains("https")) "https://$url" else url)).startForActivity()

/** 跳联系人*/
fun toContacts() = Intent(Intent.ACTION_VIEW).setData(ContactsContract.Contacts.CONTENT_URI).startForActivity()

/** 跳卸载应用*/
fun toUninstallApp(packageName1: String = packageName) = Intent(Intent.ACTION_DELETE).setData(Uri.parse("package:$packageName1")).startForActivity()

/** 跳「选择...」*/
fun toPick(type: String) = Intent(Intent.ACTION_GET_CONTENT).setType(type).addCategory(Intent.CATEGORY_OPENABLE).startForActivity()

/** 跳选择音频*/
fun toPickAudio() = toPick("audio/*")

/** 跳选择视频*/
fun toPickVideo() = toPick("video/*")

/** 跳选择图片*/
fun toPickPhoto() = toPick("image/*")

/**跳选择文件 */
fun toPickFile() = toPick("file/*")

/** 跳选择文件, 指定文件扩展名, fileExtension ==文件扩展名 */
fun toPickFile(fileExtension: String) = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension)?.let { toPick(it) }

/** 跳桌面主页*/
fun toHome() = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME).startForActivity()

/** 重启当前应用*/
fun Context.toRestartApp() = packageManager.getLaunchIntentForPackage(packageName)?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)?.let { startActivity(it) }

/** 跳百度地图       doubles(坐标系注意转换)：终点坐标( latitude   纬度   longtitude 经度)    address：目的地名称（百度地图里显示用）    mode=driving  选择导航方式 此处为驾驶       https://lbsyun.baidu.com/index.php?title=uri/api/android*/
fun toMapAppBaidu(doubles: DoubleArray, address: String) =
    Intent().setData(Uri.parse("baidumap://map/direction?destination=${doubles[0]},${doubles[1]}&destination_region=${address}&coord_type=bd09ll&mode=driving&src=${packageName}.${appName}#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end"))
        .startForActivity()

/**跳转到高德地图    doubles(坐标系注意转换)：终点坐标( latitude=纬度 、  longtitude =经度)    poiname：终点    dev：是否需要国测加密 0==不需要  1==需要            https://lbs.amap.com/api/amap-mobile/guide/android/navigation*/
fun toMapAppGaode(doubles: DoubleArray, poiname: String, dev: Int = 0) =
    Intent().setData(Uri.parse("androidamap://navi?sourceApplication=${appName}&poiname=$poiname&lat=${doubles[0]}&lon=${doubles[1]}&dev=${dev}")).startForActivity()

/**跳转到高德地图    doubles(坐标系注意转换)：终点坐标( latitude=纬度 、  longtitude =经度)    poiname：终点    dev：是否需要国测加密 0==不需要  1==需要            https://lbs.amap.com/api/amap-mobile/guide/android/navigation*/
fun toMapAppQq(doubles: DoubleArray, address: String) =
    Intent().setData(Uri.parse("qqmap://map/routeplan?type=drive&referer=${appName}&tocoord=${doubles[0]},${doubles[1]}&to=${address}")).startForActivity()

/**
 * type
 *  1    高德地图com.autonavi.minimap
 *  2    百度地图com.baidu.BaiduMap
 *  3    腾讯地图com.tencent.map
 */
/** 跳地图app  1    高德地图com.autonavi.minimap ,2    百度地图com.baidu.BaiduMap,  3    腾讯地图com.tencent.map*/
fun toMapApp(type: Int, lat: Double, lon: Double, title: String) {
    when (type) {
        1 -> {
            toMapAppGaode(getLoctionDowble(lat, lon), title)
        }
        2 -> {
            toMapAppBaidu(gcj2bd(lat, lon), title)
        }
        else -> {
            toMapAppQq(getLoctionDowble(lat, lon), title)
        }
    }
}